package angel.core.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.core.Environment;
import freemarker.core.Macro;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author Angel
 * 
 * The invoke directive is to dynamically invoke other function or macro
 * Parameters:
 * 1. target: the name of the function or macro to invoke
 * 2. arguments: the arguments required by the target
 */
public class InvokeDirective implements TemplateDirectiveModel {
	
	Logger logger = LoggerFactory.getLogger(this.getClass().getName());
	
	private static final String PARAM_NAME_TARGET="target";
	private static final String PARAM_NAME_ARGS="args";
	
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Writer out = env.getOut();
		
		String target = (String)params.get(PARAM_NAME_TARGET);
		Macro macro = (Macro)env.getTemplate().getMacros().get(target);
		if(macro == null){
			logger.error("macro["+target+"] not found");
			out.write("macro["+target+"] not found");
		}
		//env.visitMacroDef(macro);
		//ReflectionUtils.invokeMethod("accept", macro, new Object[]{this});
		
		logger.debug("Param names:"+params.keySet());
		logger.debug("Param values:"+params.values());
		Iterator paramIter = params.entrySet().iterator();
		while(paramIter.hasNext()){
			Map.Entry entry = (Map.Entry)paramIter.next();
			String paramName = (String)entry.getKey();
			TemplateModel paramValue = (TemplateModel) entry.getValue();   
			logger.debug("param["+paramName+"] = " + (paramValue));
			out.write("paramName=" + paramName);
		}		
	}
}

